package com.wenbai.servicelightluxurystickers.tools;

import com.wenbai.servicelightluxurystickers.common.RedisConstants;
import com.wenbai.servicelightluxurystickers.entity.StickPost;
import com.wenbai.servicelightluxurystickers.mapper.StickPostMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
public class RdisSyncTask {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private StickPostMapper stickPostMapper;

    @Scheduled(fixedRate = 1 * 60 * 60 * 1000)
    public void syncViewCount() {
        System.out.println("开始同步redis数据到数据库");

        // 如果redis key不存在则不做操作
        if (Boolean.FALSE.equals(redisTemplate.hasKey(RedisConstants.POST_VIEW_COUNT_KEY))) return;

        Set<String> keys = redisTemplate.keys(RedisConstants.POST_VIEW_COUNT_KEY+ "*");

        if (keys == null || keys.isEmpty()) return;

        for (String key : keys){
            Long postId = Long.parseLong(key.replace(RedisConstants.POST_VIEW_COUNT_KEY, ""));
            Integer viewCount = Integer.parseInt(redisTemplate.opsForValue().get(key).toString());
            StickPost stickPost = new StickPost();
            stickPost.setPostId(postId);
            stickPost.setViewCount(viewCount);
            stickPostMapper.updateById(stickPost);
        }

    }
}
